package com.sunye.shardingjdbc;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * @author sunye
 * @date 2023/3/11--13:53
 */
public class MyPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long> {
     //参考 https://blog.csdn.net/h1774733219/article/details/122166187
     //多张表参考 https://blog.csdn.net/pzjtian/article/details/120070542
    //doSharding方法的参数：
    //1、availableTargetNames：所有的数据存储节点
    //2、shardingValue：分片键值
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
        for (String targetName : availableTargetNames) {
            //约定cid值偶数添加到course_1表，如果cid是奇数添加到course_2表
            Long valueLong = shardingValue.getValue();
            String value = valueLong % availableTargetNames.size()+1+ "";
            if(targetName.endsWith(value)){
                return targetName;
            }
        }
        throw new RuntimeException("分片策率出错");

    }
}
